package com.jilefojing.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.jilefojing.beans.pojos.RSourceCorrelation;
import com.jilefojing.beans.pojos.base.BasePo;
import com.jilefojing.beans.pojos.enhanced.EnhancedRSourceCorrelation;
import com.jilefojing.beans.pojos.enhanced.base.BaseEnhanced;
import com.jilefojing.beans.query.RSourceCorrelationQuery;
import com.jilefojing.beans.vo.Pagination;
import com.jilefojing.context.beans.vo.UserContext;
import com.jilefojing.dao.IRSourceCorrelationDao;
import com.jilefojing.service.IRSourceCorrelationService;
import com.jilefojing.service.base.impl.BaseService;
import com.jilefojing.util.Detect;

/**
 * 
 * @author 作者 jgshun
 * @date 创建时间 2016年07月26日 10时33分29秒
 */
@Service
public class RSourceCorrelationService extends BaseService<RSourceCorrelation> implements IRSourceCorrelationService {
	private static final Logger _LOGGER = LoggerFactory.getLogger(RSourceCorrelationService.class);

	@Autowired
	private IRSourceCorrelationDao rSourceCorrelationDao;

	@Override
	public Pagination<EnhancedRSourceCorrelation> getPagination(RSourceCorrelationQuery rSourceCorrelationQuery, Pagination<EnhancedRSourceCorrelation> pagination, UserContext userContext) {
		@SuppressWarnings("unchecked")
		Pagination<RSourceCorrelation> rSourceCorrelationPagination = rSourceCorrelationDao.getPagination(rSourceCorrelationQuery, pagination.copy());
		pagination.setCount(rSourceCorrelationPagination.getCount());
		if (!Detect.notEmpty(rSourceCorrelationPagination.getItems())) {
			return pagination;
		}
		pagination.setItems(this.conventRSourceCorrelations2EnhancedRSourceCorrelations(rSourceCorrelationPagination.getItems()));
		return pagination;
	}

	@Override
	public List<EnhancedRSourceCorrelation> conventRSourceCorrelations2EnhancedRSourceCorrelations(List<RSourceCorrelation> rSourceCorrelations) {
		List<EnhancedRSourceCorrelation> enhancedRSourceCorrelations = new ArrayList<EnhancedRSourceCorrelation>();
		for (RSourceCorrelation _RSourceCorrelation : rSourceCorrelations) {
			enhancedRSourceCorrelations.add(new EnhancedRSourceCorrelation(_RSourceCorrelation));
		}
		return enhancedRSourceCorrelations;
	}

	@Override
	public List<EnhancedRSourceCorrelation> appendEnhancedRelationItem2EnhancedRSourceCorrelations(List<EnhancedRSourceCorrelation> enhancedRSourceCorrelations, UserContext userContext) {
		Map<Class<? extends BasePo>, List<Long>> relationsMap = new HashMap<Class<? extends BasePo>, List<Long>>();

		for (EnhancedRSourceCorrelation _EnhancedRSourceCorrelation : enhancedRSourceCorrelations) {
			List<Long> relationIds = relationsMap.get(_EnhancedRSourceCorrelation.getRelationType().getItemClass());
			if (!Detect.notEmpty(relationIds)) {
				relationIds = new ArrayList<Long>();
				relationsMap.put(_EnhancedRSourceCorrelation.getRelationType().getItemClass(), relationIds);
			}
			relationIds.add(_EnhancedRSourceCorrelation.getEnhancedRelationItem().getDynamicId());
		}
		Set<Entry<Class<? extends BasePo>, List<Long>>> relationsEntry = relationsMap.entrySet();
		for (Entry<Class<? extends BasePo>, List<Long>> _Entry : relationsEntry) {
			if (Detect.notEmpty(_Entry.getValue())) {
				this.appendEnhancedRelationItems2EnhancedRSourceCorrelations(_Entry, enhancedRSourceCorrelations, userContext);
			}
		}
		return enhancedRSourceCorrelations;
	}

	/**
	 * 动态添加相关资源
	 * 
	 * @param relationEntry
	 * @param enhancedRSourceCorrelations
	 * @param userContext
	 */
	private void appendEnhancedRelationItems2EnhancedRSourceCorrelations(Entry<Class<? extends BasePo>, List<Long>> relationEntry, List<EnhancedRSourceCorrelation> enhancedRSourceCorrelations,
			UserContext userContext) {
		try {
			WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();

			Class serviceClass = Class.forName("com.jilefojing.service.I" + relationEntry.getKey().getSimpleName() + "Service");

			List<BaseEnhanced> enhancedItems = null;
			for (Method _Method : serviceClass.getDeclaredMethods()) {
				if (_Method.getName().equals("getEnhanceds")) {
					enhancedItems = (List<BaseEnhanced>) _Method.invoke(webApplicationContext.getBean(serviceClass), relationEntry.getValue(), userContext);
					break;
				}
			}

			for (EnhancedRSourceCorrelation _EnhancedRSourceCorrelation : enhancedRSourceCorrelations) {
				for (BaseEnhanced _BaseEnhanced : enhancedItems) {
					if (_EnhancedRSourceCorrelation.getRelationType().getEnhancedItemClass() == _BaseEnhanced.getClass()
							&& _EnhancedRSourceCorrelation.getEnhancedRelationItem().getDynamicId() == _BaseEnhanced.getDynamicId()) {
						_EnhancedRSourceCorrelation.setEnhancedRelationItem(_BaseEnhanced);
						break;
					}
				}
			}

		} catch (ClassNotFoundException | BeansException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
			_LOGGER.error("获取资源Service出错", e1);
		}

	}
}
